package com.example.demo.zjitc.server.filter;

import com.example.demo.zjitc.server.common.JwtSecurityProperties;
import com.example.demo.zjitc.server.common.JwtTokenUtils;
import com.example.demo.zjitc.server.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

import static java.lang.Character.getType;

/**
 * Author: Wang
 * Date: 2022/1/1 19:41
 * Jwt的过滤器 用于对token的验证
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    private JwtTokenUtils jwtTokenUtils;

    public JwtAuthenticationTokenFilter(JwtTokenUtils jwtTokenUtils) {
        this.jwtTokenUtils = jwtTokenUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException, IOException, ServletException {

       // JwtSecurityProperties  =  SpringContextHolder.getBean(JwtSecurityProperties.class);
        String requestRri = httpServletRequest.getRequestURI();
        //获取request token
        String token = null;

        String bearerToken = httpServletRequest.getHeader("token");
        System.out.println(bearerToken);
        System.out.println("tokence");
     //   System.out.println(jwtTokenUtils.validateToken(bearerToken));
            boolean faly = true;
         if (bearerToken==null)
         {
             faly=false;
         }
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer"+" ")) {
            token = bearerToken.substring("1212121hsodhsdhasdhsaldhsalhdlsahdlsad1685555555555555555555555555555555555555555555555".length());
        }

        if (faly&&jwtTokenUtils.validateToken(bearerToken)) {

            System.out.println("ppp");
            Authentication authentication = jwtTokenUtils.getAuthentication(bearerToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);
        } else {
            log.debug("no valid JWT token found, uri: {}", requestRri);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);

    }


}
